package com.newland.starpos.partner.mvc.interceptor;

import com.newland.starpos.partner.utils.GenerateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Objects;

@Slf4j
public class LoggerInterceptor extends HandlerInterceptorAdapter{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
		
		StringBuilder buffer = new StringBuilder("Inbound Message\n----------------------------");
		String requestId = GenerateUtils.getRequestId();
		
		buffer.append("\nREQUEST_ID: ").append(requestId);
		buffer.append("\nAddress: ").append(request.getRequestURL());
		buffer.append("\nHttp-Method: ").append(request.getMethod());
		if(Objects.nonNull(request.getContentType()))
			buffer.append("\nContent-Type: ").append(request.getContentType());
		buffer.append("\nHeaders: ").append(getRequestHeader(request));
//		buffer.append("\nPayload: ").append(getRequestPayload(request));
		
		request.setAttribute("requestId", requestId);
		log.info(buffer.toString());
		return true;
	}

	private String getRequestHeader(HttpServletRequest request) {
		StringBuilder buffer = new StringBuilder("{");
		@SuppressWarnings("unchecked")
		Enumeration<String> headerNames = request.getHeaderNames();
		while(headerNames.hasMoreElements()) {
			String name = headerNames.nextElement();
			buffer.append(name).append("=[").append(request.getHeader(name)).append("], ");
		}
		buffer.append("}");
		return buffer.toString();
	}
	
	/*private String getRequestPayload(HttpServletRequest request) {
		ServletInputStream input; StringBuilder buffer;
		BufferedReader bufferedReader = null;
		try {
			input = request.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(input));
			buffer = new StringBuilder();
			String data;
			while(StringUtils.isNotBlank(data = bufferedReader.readLine())) {
				buffer.append(data);
			}
			request.setAttribute("payload", buffer.toString());
		} catch (IOException e) {
			return "";
		}
		return buffer.toString();
	}*/
}
